﻿//TODO: check filter, SkinFilter5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using LowLevelGraphics.ColorSpaces;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// SKinFilter5
    /// </summary>
    public class SkinFilter5 : BaseForeBackgroundColorFilter
    {
        protected bool m_bUseNormalValues = true;

        /// <summary>
        /// Initializes a new instance of the <see cref="SkinFilter5"/> class.
        /// </summary>
        public SkinFilter5()
        {
        }

        /// <summary>
        /// Gets or sets normal values
        /// </summary>
        public bool UseNormalValues
        {
            get { return m_bUseNormalValues; }
            set { m_bUseNormalValues = value; }
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            //UnsafeBitmap bitmap = new UnsafeBitmap(_bitmap);
            Color colorToSet = Color.Transparent;

            double fCr = 0.0f;

            int nHeight = _bitmap.Height;
            int nWidth = _bitmap.Width;

            int y = 0;
            int x = 0;

            Color color = Color.Transparent;

            bool bIsSkin = false;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = _bitmap.GetPixel(x, y);
                    YCbCr ycbcr = new YCbCr(color);
                    fCr = ycbcr.Cr;

                    if (m_bUseNormalValues)
                    {
                        bIsSkin = ycbcr.Cb > 75 && ycbcr.Cb < 135 && ycbcr.Cr > 130 && ycbcr.Cr < 180;
                    }
                    else
                    {
                        bIsSkin = ycbcr.Cr > 133 && ycbcr.Cr < 173 && ycbcr.Cb > 76 && ycbcr.Cb < 127 && ycbcr.Y > 50 && ycbcr.Y < 255;
                    }
    
                    if (bIsSkin)
                    {
                        colorToSet = m_ColorForeground;
                    }
                    else
                    {
                        colorToSet = m_ColorBackground;
                    }
                    _bitmap.SetPixel(x, y, colorToSet);
                }
            }
            return _bitmap;
        }

        public override object Clone()
        {
            return new SkinFilter5();
        }
    }
}
